<template>
    <div class="e-form">
        <BillTop title="租赁台账详情" @cancel="handleClose"></BillTop>
        <div class="tabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="进出场记录" name="entryExitRecords" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="维修保养记录" name="maintenanceRecords" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="其他" name="other" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.facilityAccountLease" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="设备编号：">
                                            <span>{{ formData.facilityAccountLease.equipmentNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="二维码：">
                                            <el-image style="width:100px;height:100px" :src="formData.facilityAccountLease.codePicture"></el-image>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                 <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="规格型号：">
                                            <span>{{ formData.facilityAccountLease.specificationModel }}</span>
                                        </el-form-item>
                                    </el-col>
                                     <el-col :span="12">
                                        <el-form-item label="使用单位：">
                                            <span>{{ formData.facilityAccountLease.useOrgName  }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>

                                    <el-col :span="12">
                                        <el-form-item label="设备名称：">
                                            <span>{{ formData.facilityAccountLease.equipmentName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="出租单位：">
                                            <span>{{ formData.facilityAccountLease.equipmentUnitName  }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计量单位：">
                                            <span>{{ formData.facilityAccountLease.unit }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="设备来源：">
                                            <span>{{ formData.facilityAccountLease.leaseType ? leaseTypeList.find(x=>x.value === formData.facilityAccountLease.leaseType).label : '' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="验收日期：">
                                            <span>{{ formData.facilityAccountLease.billDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="验收单号：">
                                            <span>{{ formData.facilityAccountLease.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="验收地点：">
                                            <span>{{showAddress(formData.facilityAccountLease.acceptanceSite)}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="生产厂商：">
                                            <span>{{ formData.facilityAccountLease.menufacturer }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                     <el-col :span="12">
                                        <el-form-item label="出厂编号：">
                                            <span>{{ formData.facilityAccountLease.productionNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="出厂日期：">
                                            <span>{{ formData.facilityAccountLease.productionDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="车牌编号：">
                                            <span>{{ formData.facilityAccountLease.plateNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="租赁单价（元）：">
                                            <span>{{ formData.facilityAccountLease.leasePrice }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="租赁费用（元）：">
                                            <span>{{ formData.facilityAccountLease.leaseAmount }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="设备属性：">
                                            <span>{{ formData.facilityAccountLease.nature ? deviceProperties.find(x=>x.value === formData.facilityAccountLease.nature).label:'' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="设备状态：">
                                            <span>{{ formData.facilityAccountLease.equipmentStatus ? equipStatus.find(x=>x.value === formData.facilityAccountLease.equipmentStatus).label : '' }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="设备状况：">
                                            <span>{{ formData.facilityAccountLease.equipmentCondition ? equipCondition.find(x=>x.value === formData.facilityAccountLease.equipmentCondition).label : '' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="台账状态：">
                                            <span>{{ formData.facilityAccountLease.accountStatus ? accountStatus.find(x=>x.value === formData.facilityAccountLease.accountStatus).label : ''  }}</span>
                                        </el-form-item>
                                    </el-col>
                                     <el-col :span="12">
                                        <el-form-item label="操作手：">
                                            <span>{{ formData.facilityAccountLease.operatorName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="进场时间：">
                                            <span>{{ formData.facilityAccountLease.enterDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="预计退场时间：">
                                            <span>{{ formData.facilityAccountLease.exitDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="操作手工资：">
                                            <span>{{ formData.facilityAccountLease.operatorSalary }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="entryExitRecordsCon" class="con">
                        <div class="tabs-title" id="entryExitRecords">进出场记录</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="accessRecordList"
                                border
                                style="width: 100%"
                                v-sortTable="{ 'tableData': accessRecordList, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column
                                    prop="useOrg"
                                    label="使用单位"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="enterDate"
                                    label="进场时间"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="retreatDate"
                                    label="完修/养时间"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="maintenanceRecordsCon" class="con">
                        <div class="tabs-title" id="maintenanceRecords">维修保养记录</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="maintenanceRecords"
                                :data="maintenanceLogList"
                                border
                                style="width: 100%"
                                v-sortTable="{ 'tableData': maintenanceLogList, '_this': this, 'ref': 'maintenanceRecords' }"
                            >
                                <el-table-column
                                    prop="maintenanceUnit"
                                    label="维保单位"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="maintenanceType"
                                    label="维保类型"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.maintenanceType?maintenanceType[row.maintenanceType].label:"" }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="sendToRepairTime"
                                    label="送修/养时间"
                                    width="170"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="completeRepairTime"
                                    label="完修/养时间"
                                    width="170"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="manpowerPrice"
                                    label="人工费（元）"
                                    width="130"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialsPrice"
                                    label="材料费（元）"
                                    width="130"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentPrice"
                                    label="设备费（元）"
                                    width="130"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="maintenancePrice"
                                    label="维保费（元）"
                                    width="130"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="maintenanceDetails"
                                    label="维修内容"
                                    min-width="150"
                                    align="center"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="otherCon" class="con">
                        <div class="tabs-title" id="other">其他</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                border
                                style="width: 100%"
                                :data="otherList"
                                v-sortTable="{ 'tableData': otherList, '_this': this, 'ref': 'other' }"
                            >
                                <el-table-column
                                    prop="title"
                                    label="标题"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="type"
                                    label="类型"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.type?otherType[row.type].label:'' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="generalSituation"
                                    label="概况"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="billDate"
                                    label="填报日期"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button type="primary" size="small" class="btn-blue" v-debounce
                >打印二维码</el-button
            >
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/equipAccount.js'
import '@/utils/jquery.scrollTo.min'
import { hideLoading, showLoading } from '@/utils/common'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //基础信息
                'facilityAccountLease': {
                    'acceptanceSite': '',
                    'accountStatus': '',
                    'addStatus': '',
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'categoryId': '',
                    'categoryName': '',
                    'depreciationCount': 0,
                    'easId': '',
                    'equipmentCondition': '',
                    'equipmentId': '',
                    'equipmentName': '',
                    'equipmentNo': '',
                    'equipmentStatus': '',
                    'equipmentUnitId': '',
                    'equipmentUnitName': '',
                    'isMaintenance': '',
                    'logId': '',
                    'managementOrgId': '',
                    'managementOrgName': '',
                    'menufacturer': '',
                    'nature': '',
                    'netWorth': 0,
                    'oneLevelCategoryId': '',
                    'oneLevelCategoryName': '',
                    'operatorId': '',
                    'operatorName': '',
                    'orgId': '',
                    'orgName': '',
                    'originalNo': '',
                    'ownAccountId': '',
                    'plateNo': '',
                    'productionDate': '',
                    'productionNo': '',
                    'purchaseDate': '',
                    'purchasePrice': 0,
                    'serviceLife': 0,
                    'specificationModel': '',
                    'stipulatedServiceLife': 0,
                    'unit': '',
                    'useOrgId': '',
                    'useOrgName': '',
                    'useageTime': 0
                },
            },
            billid: this.$route.query.billid,
            planSelect: [], //固定资产盘点明细选择项
            accessRecordList: [], //进出场记录
            maintenanceLogList: [], //维修保养记录
            otherList: [], //其他表格
        }
    },
    computed: {
        ...mapState({
            equipStatus: state => state.equip.equipData.equipStatus, //设备状态
            accountStatus: state => state.equip.equipData.accountStatus, //台账状态
            equipCondition: state => state.equip.equipData.equipCondition, //设备状况
            maintenanceType: state => state.equip.equipData.maintenanceType, //维保类型
            deviceProperties: state => state.equip.equipData.deviceProperties, //设备属性
            leaseTypeList: state => state.equip.equipData.leaseTypeList, //租赁类型
            otherType: state => state.equip.equipData.otherType, //其他类型
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj.label
            }
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        showAddress () {
            return value=>{
                if(!value) return ''
                const obj = JSON.parse(value)
                const address = obj.address ? obj.address.join('-') : ''
                const detail = obj.detail
                let str = ''
                if(address && detail) {
                    str = address + '-' + detail
                }else if(!address  && detail) {
                    str = detail
                }else if(address  && !detail) {
                    str = address
                }
                return str
            }
        }
    },
    components: {
    },
    created () {
        this.getDicValue()
        this.init()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'maintenanceRecords', 'entryExitRecords', 'other']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })

    },
    methods: {
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')//更新计时单位
            this.$store.dispatch('equip/setUseType')//更新使用类型
            this.$store.dispatch('equip/setMeasurementMode')//更新计量方式
            this.$store.dispatch('equip/setRunningState')//更新运行状态
            this.$store.dispatch('equip/setMaintenanceType')//更新维保类型
            this.$store.dispatch('equip/setEquipStatus')//更新设备状态
        },
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getMaintenanceRecord(),
                this.getOther(),
            ]).finally(() => {
                hideLoading()
            })
        },
        getInfo () {
            const params = {
                id: this.billid,
            }
            request.leaseAccountBaseInfo(params).then(res=>{
                this.formData = res
            })
        },
        //获取自有台账进出场记录
        getPlanList () {
            const params = {
                id: this.billid,
            }
            request.leaseEntryExitRecords(params).then(res=>{
                this.accessRecordList = res
            })
        },
        //获取自有台账维修保养记录
        getMaintenanceRecord () {
            const params = {
                id: this.billid,
            }
            request.leaseMaintenanceRecords(params).then(res=>{
                this.maintenanceLogList = res
            })
        },
        //获取自有台账其他记录
        getOther () {
            request.leaseAccountOther(this.billid).then(res=>{
                this.otherList = res.data == null ? [] : res
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/leaseAccountList')
        },
        getNowDate () {
            this.$set(
                this.formData,
                'applyTime',
                new Date()
                    .toLocaleDateString()
                    .replace(new RegExp('/', 'g'), '-')
            )
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}
</style>
